package com.ziyueyuwen.xiniao.util;

import com.alibaba.fastjson.JSONObject;
import com.ziyueyuwen.xiniao.bean.homework.ItemData;
import com.ziyueyuwen.xiniao.enums.ItemTypeEnum;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * @author jun 2018/12/19.
 */
public class QuestionUtil {
    public static List<ItemData> getItemData(JSONObject obj, HashMap<String, String> fileNameMap) throws Exception {
        List<ItemData> list = new ArrayList<>();
        for (int i = 1; i < 10; i++) {
            ItemData itemData = new ItemData();
            String str = obj.getString(String.valueOf(i));
            if (StringUtils.isBlank(str)) {
                break;
            }
            itemData.setItemType(ItemTypeEnum.TEXT);
            itemData.setItemValue(str);
            String strLowerCase = str.toLowerCase().trim();
            if (strLowerCase.endsWith(".png") || strLowerCase.endsWith(".jpg")
                    || strLowerCase.endsWith(".jpeg") || strLowerCase.endsWith(".mp3")
                    || strLowerCase.endsWith(".mp4") || strLowerCase.endsWith(".pdf")
                    || strLowerCase.endsWith(".xlsx") || strLowerCase.endsWith(".docx")
                    || strLowerCase.endsWith(".mov")) {
                if (!fileNameMap.containsKey(str)) {
                    throw new Exception("未找到文件: " + str);
                }
                itemData.setItemType(getItemType(strLowerCase));
                itemData.setItemValue("https://ziyue-xn.oss-cn-beijing.aliyuncs.com/homework/question/" + fileNameMap.get(str));
            }
            list.add(itemData);
        }
        return list;
    }

    public static ItemTypeEnum getItemType(String str) {
        str = str.toLowerCase().trim();
        int startIdx = Math.max(str.lastIndexOf("."), 0);
        str = str.substring(startIdx, str.length());
        HashMap<String, ItemTypeEnum> itemTypeEnumHashMap = new HashMap<>();
        itemTypeEnumHashMap.put(".png", ItemTypeEnum.IMG);
        itemTypeEnumHashMap.put(".jpg", ItemTypeEnum.IMG);
        itemTypeEnumHashMap.put(".jpeg", ItemTypeEnum.IMG);
        itemTypeEnumHashMap.put(".pdf", ItemTypeEnum.IMG);
        itemTypeEnumHashMap.put(".mp3", ItemTypeEnum.AUDIO);
        itemTypeEnumHashMap.put(".mp4", ItemTypeEnum.VIDEO);
        itemTypeEnumHashMap.put(".mov", ItemTypeEnum.VIDEO);
        itemTypeEnumHashMap.put(".xlsx", ItemTypeEnum.EXCEL);
        itemTypeEnumHashMap.put(".docx", ItemTypeEnum.WORD);
        if (itemTypeEnumHashMap.containsKey(str)) {
            return itemTypeEnumHashMap.get(str);
        }
        return ItemTypeEnum.TEXT;
    }
}
